package com.shqcjd.preinstallmobile.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.orhanobut.logger.Logger;
import com.pgyersdk.crash.PgyCrashManager;
import com.pgyersdk.update.PgyUpdateManager;
import com.shqcjd.preinstallmobile.R;
import com.shqcjd.preinstallmobile.api.ApiService;
import com.shqcjd.preinstallmobile.app.AppConstant;
import com.shqcjd.preinstallmobile.app.MyApp;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallmobile.jpush.TagAliasUtils;
import com.shqcjd.preinstallmobile.model.ResponseData;
import com.shqcjd.preinstallmobile.model.eventbus.FinishActivityEvent;
import com.shqcjd.preinstallmobile.model.eventbus.GoGuideEvent;
import com.shqcjd.preinstallmobile.model.eventbus.GoInspectionEvent;
import com.shqcjd.preinstallmobile.model.eventbus.IndexAllEvent;
import com.shqcjd.preinstallmobile.model.eventbus.ShowGuideEvent;
import com.shqcjd.preinstallmobile.model.eventbus.ShowInspectionEvnent;
import com.shqcjd.preinstallmobile.model.pojo.IndexBean;
import com.shqcjd.preinstallmobile.ui.adapter.FragPagerAdapter;
import com.shqcjd.preinstallmobile.ui.base.BaseActivity;
import com.shqcjd.preinstallmobile.ui.base.BasePresenter;
import com.shqcjd.preinstallmobile.ui.fragment.ExpertFragment;
import com.shqcjd.preinstallmobile.ui.fragment.HomeFragment;
import com.shqcjd.preinstallmobile.ui.fragment.InspectionFragment;
import com.shqcjd.preinstallmobile.ui.fragment.MineFragment;
import com.shqcjd.preinstallmobile.util.AppManager;
import com.shqcjd.preinstallmobile.util.IconFontTextView;
import com.shqcjd.preinstallmobile.util.PrefUtils;
import com.shqcjd.preinstallmobile.util.ToastUtils;
import com.shqcjd.preinstallmobile.util.UIUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.IAgoraAPI;
import io.agora.rtc.RtcEngine;
import io.reactivex.disposables.Disposable;

public class MainActivity extends BaseActivity {
    public  boolean isKillProcess = true;

    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.ll_home)
    LinearLayout llHome;
    @BindView(R.id.ll_inspection)
    LinearLayout llInspection;
    @BindView(R.id.ll_expert)
    LinearLayout llExpert;
    @BindView(R.id.ll_mine)
    LinearLayout llMine;
    @BindView(R.id.if_home)
    IconFontTextView ifHome;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.if_inspection)
    IconFontTextView ifInspection;
    @BindView(R.id.tv_inspection)
    TextView tvInspection;
    @BindView(R.id.if_expert)
    IconFontTextView ifExpert;
    @BindView(R.id.tv_expert)
    TextView tvExpert;
    @BindView(R.id.if_mine)
    IconFontTextView ifMine;
    @BindView(R.id.tv_mine)
    TextView tvMine;

    private List<Fragment> mFragments = new ArrayList<>();
    private Context mContext;
    private AgoraAPIOnlySignal agoraAPIOnlySignal;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }


    @Override
    public void init() {
        super.init();
        mContext = this;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);//订阅
        SetStatusBarColor();
        setTabColor(ifHome, tvHome);
        initFragment();

        initAgora();


        //蒲公英
        PgyCrashManager.register(); //推荐使用
        /** 蒲公英可选配置集成方式 **/
        new PgyUpdateManager.Builder()
                .setForced(false)                //设置是否强制提示更新
                // v3.0.4+ 以上同时可以在官网设置强制更新最高低版本；网站设置和代码设置一种情况成立则提示强制更新
                .setUserCanRetry(false)         //失败后是否提示重新下载
                .setDeleteHistroyApk(true)     // 检查更新前是否删除本地历史 Apk， 默认为true
                .register();

    }

    @Override
    public void initData() {
        getIndexData();
    }

    private void initAgora() {
        int userId = PrefUtils.getInt(this, PrefUtils.USER_ID, -1);
        agoraAPIOnlySignal = MyApp.the().getmAgoraAPI();
        //登出
        agoraAPIOnlySignal.logout();
        Logger.i("Agora 登录用户:" + userId);
        //登录声网信令系统
        agoraAPIOnlySignal.login2(getString(R.string.agora_app_id), userId + "", "_no_need_token", 0, "", 5, 3);
    }


    private void initFragment() {
        mFragments.add(HomeFragment.newInstance());
        mFragments.add(InspectionFragment.newInstance());
        mFragments.add(ExpertFragment.newInstance());
        mFragments.add(MineFragment.newInstance());

        viewpager.setAdapter(new FragPagerAdapter(getSupportFragmentManager(), mFragments));
        viewpager.setCurrentItem(0, false);
        viewpager.setOffscreenPageLimit(3);
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        setTabColor(ifHome, tvHome);
                        break;
                    case 1:
                        setTabColor(ifInspection, tvInspection);
                        break;
                    case 2:
                        setTabColor(ifExpert, tvExpert);
                        break;
                    case 3:
                        setTabColor(ifMine, tvMine);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void setTabColor(IconFontTextView icon, TextView textView) {
        ifHome.setTextColor(UIUtils.getColor(R.color.tab_nor_color));
        tvHome.setTextColor(UIUtils.getColor(R.color.tab_nor_color));
        ifInspection.setTextColor(UIUtils.getColor(R.color.tab_nor_color));
        tvInspection.setTextColor(UIUtils.getColor(R.color.tab_nor_color));
        ifExpert.setTextColor(UIUtils.getColor(R.color.tab_nor_color));
        tvExpert.setTextColor(UIUtils.getColor(R.color.tab_nor_color));
        ifMine.setTextColor(UIUtils.getColor(R.color.tab_nor_color));
        tvMine.setTextColor(UIUtils.getColor(R.color.tab_nor_color));
        icon.setTextColor(UIUtils.getColor(R.color.tab_sel_color));
        textView.setTextColor(UIUtils.getColor(R.color.tab_sel_color));
    }


    @Override
    protected void onResume() {
        super.onResume();
        addCallback();
    }



    private void addCallback() {
        agoraAPIOnlySignal.callbackSet(new AgoraAPI.CallBack() {

            @Override
            public void onLoginSuccess(int i, int i1) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Logger.i("Agora 信令登录成功:" + i + "  " + i1);
                    }
                });
            }

            @Override
            public void onLogout(int i) {
                Logger.i("Agora 信令登出");
            }

            @Override
            public void onLoginFailed(final int i) {
                Logger.e("Agora 信令onLoginFailed");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == IAgoraAPI.ECODE_LOGIN_E_NET) {
                        }
                    }
                });
            }

            @Override
            public void onError(String s, int i, String s1) {
                Logger.e("Agora 信令onError s:" + s + " i:" + i + " s1:" + s1);
                if (i == 208) {//用户已登录，再次发起登录会触发该错误 可以忽视该错误

                }
            }

            //            呼叫取消时的回调
            @Override
            public void onInviteEndByPeer(String channelID, String account, int uid, String extra) {
                super.onInviteEndByPeer(channelID, account, uid, extra);
                Logger.i("AgoraService：呼叫取消 房间:" + channelID);
//                if (AnswerActivity.getInstance() != null) {
//                    AppManager.getAppManager().finishActivity(AnswerActivity.class);
//                }
            }

            //收到对方呼叫时调用
            @Override
            public void onInviteReceived(String channelID, String account, int uid, String extra) {
                super.onInviteReceived(channelID, account, uid, extra);
                Logger.i("AgoraService：收到呼叫 房间:" + channelID + " 账号:" + account + " 备注:" + extra);
                Intent intent = new Intent(MyApp.getmContext(), AnswerActivity.class);
                intent.putExtra("channelID", channelID);
                intent.putExtra("callerId", account);//主叫方id
                intent.putExtra("info", extra);//主叫方id
                startActivity(intent);

            }

        });
    }

    /**
     * 获取首页内容
     */
    private void getIndexData() {
        ApiService.index()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<IndexBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在获取信息");
                    }

                    @Override
                    public void _onNext(ResponseData<IndexBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            EventBus.getDefault().post(new IndexAllEvent(retData.data));
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }


    @OnClick({R.id.ll_home, R.id.ll_inspection, R.id.ll_expert, R.id.ll_mine})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_home://首页
                viewpager.setCurrentItem(0);
                setTabColor(ifHome, tvHome);
                break;
            case R.id.ll_inspection://巡检
                viewpager.setCurrentItem(1);
                setTabColor(ifInspection, tvInspection);
                break;
            case R.id.ll_expert://专家
                viewpager.setCurrentItem(2);
                setTabColor(ifExpert, tvExpert);
                break;
            case R.id.ll_mine://我的
                viewpager.setCurrentItem(3);
                setTabColor(ifMine, tvMine);
                break;
        }
    }

    public long preTime;
    public final long TWO_SECOND = 2 * 1000;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - preTime > TWO_SECOND) {
                ToastUtils.show(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT);
                // 更新时间
                preTime = System.currentTimeMillis();

            } else {
                MainActivity.this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出登录
     */
    private void signOut() {
        agoraAPIOnlySignal.logout();//退出信令
        isKillProcess = false;
        PrefUtils.setBoolean(this, PrefUtils.FIRST_LOGIN, false);
        PrefUtils.setInt(this, PrefUtils.USER_ID, -1);
        PrefUtils.setString(this, PrefUtils.USER_CODE, "");
        PrefUtils.setString(this, PrefUtils.USER_NAME, "");
        PrefUtils.setString(this, PrefUtils.PHONE_NUMBER, "");
        PrefUtils.setString(this, PrefUtils.USER_ICON, "");
        PrefUtils.setString(this, AppConstant.TOKEN_KEY, "");
        PrefUtils.setInt(this, PrefUtils.USER_TYPE, -1);
        PrefUtils.setString(this, PrefUtils.USER_ACCOUNT, "");
        PrefUtils.setString(this, PrefUtils.USER_PWD, "");
        new TagAliasUtils().TagAliasUtils("");
        AppManager.getAppManager().finishAllActivity();
        Intent it = new Intent(this, LoginActivity.class);
        startActivity(it);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//解除订阅
        if (isKillProcess) {
            RtcEngine.destroy();//销毁rtc实例
            android.os.Process.killProcess(android.os.Process.myPid());//杀死进程
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onFinishActivityEvent(FinishActivityEvent event) {
        showOutDialog();
    }


    @Subscribe(threadMode = ThreadMode.MAIN) //跳转巡检
    public void goInspectionEvent(GoInspectionEvent event) {
        viewpager.setCurrentItem(1);
        setTabColor(ifInspection, tvInspection);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //跳转远程指导
    public void goGuideEvent(GoGuideEvent event) {
        viewpager.setCurrentItem(2);
        setTabColor(ifExpert, tvExpert);
    }

    /**
     * 是否显示巡检模块
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showInspection(ShowInspectionEvnent event) {
        if (event.isShow) {
            llInspection.setVisibility(View.VISIBLE);
        } else {
            llInspection.setVisibility(View.GONE);
        }
    }

    /**
     * 是否显示专家模块
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showInspection(ShowGuideEvent event) {
        if (event.isShow) {
            llExpert.setVisibility(View.VISIBLE);
        } else {
            llExpert.setVisibility(View.GONE);
        }

    }

    private void showOutDialog(){
        final MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(R.layout.custome_out_view, false)
                .show();

        View customeView = dialog.getCustomView();

        TextView cancel = customeView.findViewById(R.id.tv_cancel);
        TextView confirm = customeView.findViewById(R.id.tv_confirm);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                signOut();
            }
        });
    }


}
